// 任务管理应用
document.addEventListener('DOMContentLoaded', function() {
    // DOM元素
    const taskInput = document.getElementById('taskInput');
    const addTaskBtn = document.getElementById('addTaskBtn');
    const taskList = document.getElementById('taskList');
    const filterBtns = document.querySelectorAll('.filter-btn');
    const taskCount = document.getElementById('taskCount');
    const completedCount = document.getElementById('completedCount');
    
    // 任务数组
    let tasks = [];
    
    // 从本地存储加载任务
    function loadTasks() {
        const storedTasks = localStorage.getItem('tasks');
        if (storedTasks) {
            tasks = JSON.parse(storedTasks);
            renderTasks();
            updateStats();
        }
    }
    
    // 保存任务到本地存储
    function saveTasks() {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }
    
    // 添加新任务
    function addTask() {
        const text = taskInput.value.trim();
        if (text === '') {
            alert('请输入任务内容');
            return;
        }
        
        const newTask = {
            id: Date.now(),
            text: text,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        tasks.push(newTask);
        taskInput.value = '';
        saveTasks();
        renderTasks();
        updateStats();
    }
    
    // 删除任务
    function deleteTask(id) {
        tasks = tasks.filter(task => task.id !== id);
        saveTasks();
        renderTasks();
        updateStats();
    }
    
    // 切换任务完成状态
    function toggleTask(id) {
        tasks = tasks.map(task => {
            if (task.id === id) {
                return { ...task, completed: !task.completed };
            }
            return task;
        });
        saveTasks();
        renderTasks();
        updateStats();
    }
    
    // 编辑任务
    function editTask(id, newText) {
        if (newText.trim() === '') {
            alert('任务内容不能为空');
            return;
        }
        
        tasks = tasks.map(task => {
            if (task.id === id) {
                return { ...task, text: newText.trim() };
            }
            return task;
        });
        saveTasks();
        renderTasks();
    }
    
    // 渲染任务列表
    function renderTasks(filter = 'all') {
        // 清空当前任务列表
        taskList.innerHTML = '';
        
        // 筛选任务
        let filteredTasks = tasks;
        if (filter === 'pending') {
            filteredTasks = tasks.filter(task => !task.completed);
        } else if (filter === 'completed') {
            filteredTasks = tasks.filter(task => task.completed);
        }
        
        // 如果没有任务，显示空状态
        if (filteredTasks.length === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'empty-state';
            emptyState.innerHTML = `
                <h3>${filter === 'all' ? '还没有任务' : filter === 'pending' ? '没有待完成的任务' : '没有已完成的任务'}</h3>
                <p>${filter === 'all' ? '添加一个新任务开始吧！' : ''}</p>
            `;
            taskList.appendChild(emptyState);
            return;
        }
        
        // 渲染任务
        filteredTasks.forEach(task => {
            const taskItem = document.createElement('div');
            taskItem.className = `task-item ${task.completed ? 'completed' : ''}`;
            taskItem.innerHTML = `
                <input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
                <span class="task-text">${task.text}</span>
                <div class="task-actions">
                    <button class="edit-btn">编辑</button>
                    <button class="delete-btn">删除</button>
                </div>
            `;
            
            // 添加事件监听器
            const checkbox = taskItem.querySelector('.task-checkbox');
            const editBtn = taskItem.querySelector('.edit-btn');
            const deleteBtn = taskItem.querySelector('.delete-btn');
            const taskText = taskItem.querySelector('.task-text');
            
            checkbox.addEventListener('change', () => toggleTask(task.id));
            
            deleteBtn.addEventListener('click', () => deleteTask(task.id));
            
            editBtn.addEventListener('click', () => {
                const currentText = taskText.textContent;
                const newText = prompt('编辑任务:', currentText);
                if (newText !== null) {
                    editTask(task.id, newText);
                }
            });
            
            taskList.appendChild(taskItem);
        });
    }
    
    // 更新任务统计
    function updateStats() {
        const totalTasks = tasks.length;
        const completedTasks = tasks.filter(task => task.completed).length;
        
        taskCount.textContent = `总任务: ${totalTasks}`;
        completedCount.textContent = `已完成: ${completedTasks}`;
    }
    
    // 筛选任务
    function filterTasks(filter) {
        // 更新活动按钮
        filterBtns.forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.filter === filter) {
                btn.classList.add('active');
            }
        });
        
        // 渲染筛选后的任务
        renderTasks(filter);
    }
    
    // 事件监听器
    addTaskBtn.addEventListener('click', addTask);
    
    taskInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            addTask();
        }
    });
    
    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            filterTasks(this.dataset.filter);
        });
    });
    
    // 初始化应用
    loadTasks();
});